package com.renbang.utils.drawandindex;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.renbang.model.art.ArtJian;

public class IndexManager{
    private static String INDEX_DIR = "F:/简书";
    private static Analyzer analyzer = null;
    private static Directory directory = null;
    private static IndexWriter indexWriter = null;
    //当数据库有新增，或者第一次创建索引时。用这个方法
    public static boolean createIndex(List<ArtJian> list) throws Exception{
    	File file =	new File(INDEX_DIR);
//    	deleteDir(file);//删除
    	directory = FSDirectory.open(file);//索引文件夹
    	analyzer = new IKAnalyzer();
		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);
		indexWriter = new IndexWriter(directory, config);
		//遍历数据库所有数据
		for (ArtJian article : list) {
			 Document doc=new Document(); 
			//StringField不分词，TextField分词
			 doc.add(new StringField("aticleId", article.getId()+"", Store.YES));
	         doc.add(new StringField("authorName", article.getAuthorName(), Store.YES)); 
	         doc.add(new TextField("title", article.getTitle(), Store.YES)); 
	         doc.add(new TextField("content", article.getContent(), Store.YES)); 
	         indexWriter.addDocument(doc); 
//	         indexWriter.commit(); 
		}
		int count =indexWriter.numDocs();  
//        indexWriter.forceMerge(100);
        System.out.println("->存入索引库的数量："+count);  
        indexWriter.close(); 
        analyzer.close();
        directory.close();
		return true;
    }
    //当数据库有数据被修改时，需要用到更新索引
    public static boolean updateIndex(List<ArtJian> list) throws Exception{
    	analyzer = new IKAnalyzer();
	 	Directory directory = FSDirectory.open(new File(INDEX_DIR));//索引文件夹
		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);
		indexWriter = new IndexWriter(directory, config);
		for (ArtJian article : list) {
		Document doc=new Document(); 
		//StringField不分词，TextField分词
		 doc.add(new StringField("aticleId", article.getId()+"", Store.YES));
         doc.add(new StringField("authorName", article.getAuthorName(), Store.YES)); 
         doc.add(new TextField("title", article.getTitle(), Store.YES)); 
         doc.add(new TextField("content", article.getContent(), Store.YES)); 
         indexWriter.updateDocument(new Term("aticleId", article.getId()+""), doc);
		}
		indexWriter.close(); 
		analyzer.close();
        directory.close();
		return false;
    }
    
    //当数据库有数据被删除时，需要用到删除索引
    public static boolean delIndex(List<ArtJian> list) throws Exception{
	 	directory = FSDirectory.open(new File(INDEX_DIR));//索引文件夹
	 	analyzer = new IKAnalyzer();
		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);
		indexWriter = new IndexWriter(directory, config);
		for (ArtJian article : list) {
    	indexWriter.deleteDocuments(new Term("aticleId", article.getId()+""));//删除索引
		}
		indexWriter.close();
		analyzer.close();
        directory.close();
		return false;
    }
    //查询索引
    public static void searchIndex(String text){
        try{
            directory = FSDirectory.open(new File(INDEX_DIR));//索引文件夹
            analyzer = new IKAnalyzer();
            
            DirectoryReader ireader = DirectoryReader.open(directory);
            IndexSearcher isearcher = new IndexSearcher(ireader);
            QueryParser parser = new QueryParser(Version.LUCENE_40, "title", analyzer);
            parser.setDefaultOperator(QueryParser.AND_OPERATOR);//设置默认逻辑‘或’查询
            Query query = parser.parse(text);
            
//            String[] fields = new String[]{"log_content","user_name"};
//            MultiFieldQueryParser multiFieldQueryParser = new MultiFieldQueryParser(Version.LUCENE_40, fields, analyzer);
//            Query query1 = multiFieldQueryParser.parse(text);
//            BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
//                                                                 BooleanClause.Occur.MUST};
//            Query query1 = MultiFieldQueryParser.parse(Version.LUCENE_40, text, fields, flags, analyzer); 
//            TopDocs docs =isearcher.search(query,null, 10);//查找 
            ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
            for (int i = 0; i < hits.length; i++) {
                Document hitDoc = isearcher.doc(hits[i].doc);
                System.out.println(hitDoc.get("aticleId"));
                System.out.println(hitDoc.get("authorName"));
                System.out.println(hitDoc.get("title"));
                System.out.println(hitDoc.get("content"));
            }
            ireader.close();
            analyzer.close();
            directory.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
    	//如果文件夹为空，创建索引。否则直接查询
    	File file = new File(INDEX_DIR);
//    	System.out.println();
//    	if(file.list().length==0){
    		 try {
//    			 List<Map<String,String>> list = new ArrayList<Map<String,String>>();
//    			 List<Map<String,String>> list = DBUtils.getList("sys_Log", "log_id,log_content,user_name", "");
//    			 createIndex(list);
//    			 Map<String,String> map = new HashMap<String, String>();
//    			 map.put("log_id", "222");
//    			 map.put("log_content", "系统登出");
//    			 map.put("user_name", "大哥");
//    			 list.add(map);
////    			 delIndex(list);
//    			 updateIndex(list);//更新索引
			} catch (Exception e) {
				e.printStackTrace();
			}
//    	}
//        searchIndex("系统登出");
    }
	
    
    public static boolean deleteDir(File file){
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for(int i=0; i<files.length; i++){
                deleteDir(files[i]);
            }
        }
        file.delete();
        return true;
    }
}